//
//  WXViewController.m
//  WebJavascripeBridge
//
//  Created by xwx on 2018/8/27.
//  Copyright © 2018年 xwx. All rights reserved.
//

#import "WXViewController.h"
#import <WebKit/WebKit.h>
#import "WKWebViewJavascriptBridge.h"
#import "QRcodeViewController.h"


#define ZOOMWAY_SCREEN_BOUNDS [UIScreen mainScreen].bounds
#define ZOOMWAY_SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define ZOOMWAY_SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface WXViewController ()<WKNavigationDelegate,WKUIDelegate,WKNavigationDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong)WKWebView *webview;
@property(nonatomic, strong)WKWebViewJavascriptBridge *bridge;
@property(nonatomic,strong)UIImagePickerController *imagePickerController;
@property(nonatomic,copy)WVJBResponseCallback responseCallback;

@end

@implementation WXViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"测试";
    self.view.backgroundColor = [UIColor whiteColor];
    [self _initViews];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)_initViews{
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
   // preferences.minimumFontSize = 30.0;
    configuration.preferences = preferences;
    
    
    self.webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    self.webview.navigationDelegate = self;
    self.webview.UIDelegate = self;
    [self.view addSubview:self.webview];
    
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSString *appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [self.webview loadHTMLString:appHtml baseURL:baseURL];
    
    //搭桥
    self.bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webview];
    [self.bridge setWebViewDelegate:self];
    
    [self _initScanView];
    [self _initCreameAction];
    [self _initNavAction];
    
    
    
}

#pragma mark - WKNavigationDelegate
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {

}
//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

}

#pragma mark -注册的方法

#pragma mark - 注册的导航栏方法

-(void)_initNavAction{
    
    [self.bridge registerHandler:@"TheNavBarColorChange" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        CGFloat r =  (arc4random()%255) / 255.0;
        CGFloat g =  (arc4random()%255) / 255.0;
        CGFloat b =  (arc4random()%255) / 255.0;
        UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:1];
        self.navigationController.navigationBar.barTintColor = color;
        
    }];
    
    
    //改变导航栏的标题
    [self.bridge registerHandler:@"TheNavBarTitleChange" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        NSString *title = (NSString *)data;
        if (title.length == 0) {
            return;
        }
        self.title = title;
        if (responseCallback) {
            responseCallback(@"success");
        }
    }];
    
}

#pragma mark -注册相册的方法

-(void)_initCreameAction{
    
    __weak WXViewController *weakself = self;
    
    //获取照片的方法
    [self.bridge registerHandler:@"getThePhotoFromPhone" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        
        weakself.responseCallback = responseCallback;
        
        [ac addAction:[UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            [self getPhotoType:1];
            
        }]];
        [ac addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            [self getPhotoType:2];
        }]];
        
        [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
            
        }]];
        
        
        [self presentViewController:ac animated:YES completion:nil];
        
    }];
    
}

-(void)getPhotoType:(NSInteger)type

{
    _imagePickerController = [[UIImagePickerController alloc]init];
    
    _imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    _imagePickerController.delegate = self;
    _imagePickerController.allowsEditing = YES;
    
    if(type == 1){
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else{
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    [self presentViewController:_imagePickerController animated:YES completion:^{
        
    }];
}



#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.image"]) { //选择了图片
        
        
        UIImage *image;
        
        if ([info objectForKey:UIImagePickerControllerEditedImage])
        {
            
            image = [info objectForKey:UIImagePickerControllerEditedImage];
        }
        else if ([info objectForKey:UIImagePickerControllerOriginalImage])
        {
            
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
            
        }
        
        NSData *datap = UIImageJPEGRepresentation(image, 0.2f);
        
        NSString *encodedImageStr = [datap base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        
        NSString *imgType = [self typeForImageData:datap];
        
        NSString  *strX = [NSString stringWithFormat:@"data:image/%@;base64,%@",imgType,encodedImageStr];
        
        NSDictionary *dicb = @{
                               @"data":strX
                               
                               };
        
        if (_responseCallback) {
            
            _responseCallback(dicb);
        }
        
        [picker dismissViewControllerAnimated:YES
                                   completion:^{}];
        
    }
}

//判断图片的类型
- (NSString *)typeForImageData:(NSData *)data {
    
    uint8_t c;
    
    [data getBytes:&c length:1];
    
    switch (c) {
            
        case 0xFF:
            
            return @"jpeg";
            
        case 0x89:
            
            return @"png";
            
        case 0x47:
            
            return @"gif";
            
        case 0x49:
            
        case 0x4D:
            
            return @"tiff";
    }
    
    return nil;
    
}

#pragma mark -扫描二维码

-(void)_initScanView{
    
    [self.bridge registerHandler:@"resignScanCodeAction" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        QRcodeViewController *scanVC = [[QRcodeViewController alloc]init];
        
        scanVC.block = ^(NSString *result){
            
            NSDictionary *dic = @{
                                  @"error":@"",
                                  @"data":result
                                  };
            
            if (responseCallback) {
                responseCallback(dic);
            }
        };
        
        [self.navigationController pushViewController:scanVC animated:YES];
        
    }];
}


-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler();
        
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(NO);
        
    }])];
    
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(YES);
        
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.text = defaultText;
        
    }];
    
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(alertController.textFields[0].text?:@"");
        
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}


@end
